<template>
    <div class="app-container">
        <el-row :gutter="0">
            <!--专病数据-->
            <el-form class="formBox formBox1  searchForm" :model="queryParams" ref="queryForm" size="small"
                :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label-width="0px">
                    <el-radio-group v-model="treatRadio" size="mini" fill="red" @input="changeTreatRadio">
                        <el-radio-button label="开单业务"></el-radio-button>
                        <el-radio-button label="治疗业务"></el-radio-button>

                    </el-radio-group>
                </el-form-item>

                <el-form-item label="选择医院">
                    <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="180px"
                        ref="department" :isUserAll="true">
                    </department>
                </el-form-item>
                <el-form-item label="选择时间">
                    <el-date-picker v-model="dateRange" style="width: 200px;margin-right:10px;"
                        :picker-options="pickerOptions" value-format="yyyy-MM-dd" type="daterange" size="mini"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleQuery"
                        :clearable="false"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
                    <el-button icon="el-icon-printer" size="mini" type="success" @click="handleExport">导出</el-button>
                </el-form-item>
            </el-form>
            <div class="formBox searchForm" ref="statisticalTable" style="margin-bottom:0px!important;">
                <!-- summary-method="getSummary" :summary-method="getSummaries"-->
                <el-table border v-loading="loading" :data="tableLists" show-summary :summary-method="getSummaries"
                    id="out-table" :border="true" style="width: 100%" stripe ref="table" :height="statisticalTableH">
                    <!--                <el-table-column type="selection" width="50" align="center" />-->
                    <el-table-column label="序号" align="center" type="index" width="50" fixed>
                        <template slot-scope="scope">
                            <span>{{ getIndex(scope.$index) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="员工账号" align="center" prop="treatmentDoctor" :show-overflow-tooltip="true"
                        width="80" fixed />
                    <el-table-column label="员工姓名" align="center" prop="nickName" :show-overflow-tooltip="true"
                        width="130" fixed />


                    <el-table-column :label="item.treatmentPlan" align="center" v-for="(item, index) in planList"
                        :key="item.id">


                        <el-table-column align="center" prop="countPerson" label="人次（次）" width="80" :id="item.sPlanId">
                            <template slot-scope="scope">
                                <span v-if="scope.row.treatmentCount[index].countPerson"
                                    style="color:red;font-size:16px">{{
            scope.row.treatmentCount[index].countPerson }}</span>
                                <span v-else>-</span>
                                <!-- <span>{{ getTbaleCloum(scope.row.treatmentCount, item.sPlanId, item).countPerson }}</span> -->
                            </template>
                        </el-table-column>
                        <el-table-column prop="treatmentPrice" align="center" label="收入（元）" width="100"
                            :id="item.sPlanId">
                            <template slot-scope="scope">
                                <span v-if="scope.row.treatmentCount[index].treatmentPrice"
                                    style="color:red;font-size:16px">{{
            scope.row.treatmentCount[index].treatmentPrice }}</span>
                                <span v-else>-</span>
                                <!-- <span>{{ getTbaleCloum(scope.row.treatmentCount, item.sPlanId, item).treatmentPrice }}</span> -->
                            </template>
                        </el-table-column>
                    </el-table-column>







                </el-table>
                <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
            </div>


        </el-row>
    </div>
</template>

<script>
//引入安装的依赖
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
import XLSXD from "xlsx-style";

import department from "@/views/components/department/index.vue";
import { statisticsTreatmentByTime, statisticsDoctorTreatmentByTime } from "@/api/system/specialCom";
import {
    listPlan
} from "@/api/system/plan";
export default {
    name: "doctorSum",
    dicts: [

    ],
    components: { department },
    data() {
        return {
            treatRadio: "治疗业务",
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now() - 8.64e6;  //如果没有后面的-8.64e6就是不可以选择今天的
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        const end = date;
                        const start = date;
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '前天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 2);
                        const end = date;
                        const start = date;
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近六个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近1年',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            // 方案表格数据
            planList: null,

            tableLists: [],
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 日期范围
            dateRange: [],
            // 表单参数
            // form: {},
            form: {

            },
            pageNum: 1,
            pageSize: 10,
            // 查询参数
            queryParams: {
                // pageNum: 1,
                // pageSize: 10,
                hospitalId: '',
                deptId: '',
            },
            statisticalTableH: undefined
        };
    },
    watch: {},
    computed: {
        defaultTime: function () {//默认当月1号 到 现在
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            month = month > 9 ? month : "0" + month;
            day = day < 10 ? "0" + day : day;
            let day0 = '01';
            let today = year + "-" + month + "-" + day;
            let firtsDay = year + "-" + month + "-" + day0;
            return [firtsDay, today];
        },
    },
    async created() {

    },
    mounted() {
        this.dateRange = this.defaultTime
        this.changeHeight()
    },
    updated() {
        this.$nextTick(() => {

            this.$refs.table.doLayout()
        })
    },
    methods: {
        changeTreatRadio(e) {
            this.treatRadio=e
            this.getlistPlans()
        },
        changeHeight() {
            if (this.$refs.statisticalTable) {
                const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
                let h = statisticalTableObj.top + 30
                this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
            } else {
                this.statisticalTableH = '500px'
            }
        },
        getSummaries(param) {
            let that = this
            const { columns, data } = param;
            const sums = [];
            // console.log(columns)
            // console.log(data)
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                if (index === 1) {
                    sums[index] = '总人次：'
                    return
                }
                if (index === 2) {
                    sums[index] = '总收入：'
                    return
                }
                let indexof = parseInt((index - 3) / 2)
                // console.log(indexof)

                const values = data.map(item => Number(item.treatmentCount[indexof][column.property]));
                // console.log(values)
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return Math.floor(prev * 100) / 100 + Math.floor(curr * 100) / 100;
                        } else {
                            return Math.floor(prev * 100) / 100;
                        }
                    }, 0);
                    sums[index] += '';
                } else {
                    sums[index] = '';
                }


            });
            // console.log("dhjahjdjhajdjas合计**************")
            // console.log(sums)
            let sums1 = 0
            let sums2 = 0
            for (var i = 3; i < sums.length; i++) { // 从角标3开始
                if (i % 2 === 0) {
                    sums2 = Math.floor((sums2 + Number(sums[i])) * 100) / 100
                } else {
                    sums1 = Math.floor((sums1 + Number(sums[i])) * 100) / 100
                }

            }
            sums[1] = '总人次：' + sums1 + "(次)"
            sums[2] = '总收入：' + sums2 + "(元)"

            return sums;
        },
        /** 导出按钮操作 */
        // handleExport() {
        //     let tables = document.getElementById('out-table').cloneNode(true) // 重点
        //     tables.removeChild(tables.querySelector(".el-table__fixed")) // 重点
        //     let table_book = XLSX.utils.table_to_book(tables)
        //     var table_write = XLSX.write(table_book, {
        //         bookType: 'xlsx',
        //         bookSST: true,
        //         type: 'array',
        //     })
        //     try {
        //         FileSaver.saveAs(
        //             new Blob([table_write], { type: 'application/octet-stream' }),
        //             `治疗业务统计_${this.dateRange[0]}~${this.dateRange[1]}.xlsx`
        //         )
        //     } catch (e) {
        //         if (typeof console !== 'undefined') console.log(e, table_write)
        //     }
        //     return table_write
        // },
        handleExport() {
            let tables = document.getElementById('out-table').cloneNode(true) // 重点
            if (tables.querySelector(".el-table__fixed")) {
                tables.removeChild(tables.querySelector(".el-table__fixed")) // 重点
            }
            let wb = XLSX.utils.table_to_book(tables, { sheet: `${this.treatRadio}统计` })
            this.setExlStyle(wb['Sheets'][`${this.treatRadio}统计`])
            //合并单元格边框补齐
            this.addRangeBorder(wb['Sheets'][`${this.treatRadio}统计`]['!merges'], wb['Sheets'][`${this.treatRadio}统计`])
            var ws = XLSXD.write(wb, {
                type: "buffer"
            });
            try {
                FileSaver.saveAs(
                    new Blob([ws], { type: "application/octet-stream" }),
                    `${this.treatRadio}统计_${this.dateRange[0]}~${this.dateRange[1]}.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, ws);
            }
            return ws;

        },
        setExlStyle(data) {
            let borderAll = {//单元格外侧框线
                top: {
                    style: 'thin',
                },
                bottom: {
                    style: 'thin'
                },
                left: {
                    style: 'thin'
                },
                right: {
                    style: 'thin'
                }
            };
            data['!cols'] = [];
            for (let key in data) {
                if (data[key] instanceof Object) {
                    data[key].s = {
                        border: borderAll,
                        alignment: {
                            horizontal: 'center',//水平居中对齐
                            vertical: 'center'
                        },
                        font: {
                            sz: 11
                        },
                        bold: true,
                        numFmt: 0
                    }
                    data['!cols'].push({ wpx: 115 });
                }
            }
            return data;
        },
        addRangeBorder(range, ws) {
            let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
            range.forEach(item => {
                let startRowNumber = Number(item.s.c),
                    endRowNumber = Number(item.e.c);
                for (let i = startRowNumber; i <= endRowNumber; i++) {
                    for (let j = Number(item.s.r) + 1; j <= Number(item.e.r); j++) {
                        ws[`${arr[i]}${j + 1}`] = { s: { border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } } } };
                    }
                }

            })
            return ws;

        },

        /** 查询方案列表 */
        getlistPlans() {
            this.loading = true;
            let params = {
                pageNum: 1,
                pageSize: 9999,
                status: 0,
                hospitalId: this.queryParams.hospitalId,
                planCategoryId: "2"
            }
            listPlan(params).then(
                (response) => {
                    let data = response.rows;
                    // console.log(data)
                    let planData = []
                    data.forEach(function (ele) {
                        let obj = {}
                        obj.sPlanId = ele.planId
                        obj.countPerson = 0
                        obj.treatmentPlan = ele.medicalEquipment
                        obj.treatmentPrice = 0
                        planData.push(obj)
                    })
                    this.planList = planData;
                    this.loading = false;
                    this.getList()
                }
            );
        },
        refreshData(data) {
            // console.log(data)
            if (data.hospitalId) {
                this.queryParams.hospitalId = data.hospitalId
                this.queryParams.deptId = data.deptId

            } else {
                this.queryParams.hospitalId = ''
            }
            this.getlistPlans()
        },
        getList() {
            let that = this
            if (this.queryParams.hospitalId) {
                that.loading = true;
                let params = {
                    startTime: that.dateRange[0],
                    endTime: that.dateRange[1],
                    ...that.queryParams
                }
                if (that.treatRadio == '治疗业务') {
                    statisticsTreatmentByTime(params).then((response) => {
                        if (response.code == 200) {
                            let data = response.data;
                            // console.log(data)
                            let arrB = data
                            let arrC = []
                            arrB.forEach(function (ele, index) {//最外层用户
                                let obj = {}
                                obj.treatmentDoctor = ele.treatmentDoctor
                                obj.nickName = ele.nickName
                                obj.treatmentCount = []
                                let treatmentCount = ele.treatmentCount
                                that.planList.forEach(function (planele, index1) {//大集合
                                    let item = treatmentCount.find(v => v.sPlanId == planele.sPlanId)
                                    if (item) {
                                        obj.treatmentCount.push(item)
                                    } else {
                                        obj.treatmentCount.push(planele)
                                    }

                                })
                                arrC.push(obj)
                            })
                            this.tableLists = arrC
                            // arr = arr.filter(v => v.num < 20).map(v => v.num)
                        }
                        that.loading = false;
                    });
                } else {
                    statisticsDoctorTreatmentByTime(params).then((response) => {
                        if (response.code == 200) {
                            let data = response.data;
                            // console.log(data)
                            let arrB = data
                            let arrC = []
                            arrB.forEach(function (ele, index) {//最外层用户
                                let obj = {}
                                obj.treatmentDoctor = ele.treatmentDoctor
                                obj.nickName = ele.nickName
                                obj.treatmentCount = []
                                let treatmentCount = ele.treatmentCount
                                that.planList.forEach(function (planele, index1) {//大集合
                                    let item = treatmentCount.find(v => v.sPlanId == planele.sPlanId)
                                    if (item) {
                                        obj.treatmentCount.push(item)
                                    } else {
                                        obj.treatmentCount.push(planele)
                                    }

                                })
                                arrC.push(obj)
                            })
                            this.tableLists = arrC
                            // arr = arr.filter(v => v.num < 20).map(v => v.num)
                        }
                        that.loading = false;
                    });
                }

            } else {
                that.loading = false;
            }
        },
        getTbaleCloum(arrAList, id, obj) {
            let that = this
            let item = arrAList.find(v => v.sPlanId == id)
            if (item) {
                return item
            } else {
                return obj
            }
        },
        // 真实序号计算（计算分页影响）
        getIndex(index) {
            return (this.pageNum - 1) * this.pageNum + index + 1;
        },

        // 取消按钮
        cancel() {

        },
        // 表单重置
        reset() {

        },
        /** 搜索按钮操作 */
        handleQuery() {

            // this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            if (this.$refs.department) {
                this.$refs.department.reset()
            }
        },
    },
};
</script>
<style scoped lang="scss">
::v-deep .statisticalTable .el-table .cell {
    font-size: 12px;
}
</style>
